/*
 * Copyright (c) 2018 feeyo All Rights Reserved.
 * ProjectName: feeyoframework
 * FileName: AudioPlayer.kt
 * Auther: erik
 * Date: 12/26/18 4:57 PM
 * Version: 1.0
 * LastModified: 12/26/18 4:57 PM
 */

package com.feeyo.groundservice.easyphotoplus.audio

import android.media.MediaPlayer
import java.lang.Exception
import java.lang.IllegalStateException

class AudioPlayer {

    private val player by lazy { MediaPlayer() }

    private var finishListener: IFinishListener? = null

    /**
     * 播放音频文件
     * @param path 文件路径或者http url
     * @param listener 播放完成listener
     */
    fun play(path: String, listener: IFinishListener? = null) {
        /*if (!FileUtils.isFileExist(path)) {
            println("$path is not exist!")
            return
        }*/

        finishListener = listener
        try {
            player.reset()
            player.setDataSource(path)
            player.prepareAsync()
            player.setOnPreparedListener {
                player.start()
            }
            finishListener?.let { _ ->
                player.setOnCompletionListener {
                    finishListener!!.onFinish()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 停止播放
     */
    fun stop() {
        player.pause()
        player.seekTo(0)
        finishListener = null
    }

    fun release() {
        try {
            if (player.isPlaying) {
                player.stop()
            }
        } catch (e: IllegalStateException) {
            e.printStackTrace()
        }
        player.release()
        finishListener = null
    }


    /**
     * 是否在播放
     */
    fun isPlaying(): Boolean {
        return player.isPlaying
    }

    interface IFinishListener {
        fun onFinish()
    }
}